import React, { useMemo, useRef } from "react";
import { Badge } from "antd";

import { helper } from "@yaf/utils";
import { ProTable, type TableType, type IProTableRef } from "@yaf/pro-ui";
import { useThemeToken, getEnv } from "@/constants";

import { getDataAction, CreateOrEdit, filterItems } from './proTableDriver';
import { RespDataType } from '../api';

const List: React.FC = () => {
  const { themeToken } = useThemeToken();
  const proTableRef = useRef<IProTableRef>();
  const columns = useMemo(() => getColumns(), []);

  return <ProTable
    ref={proTableRef}
    dataAction={getDataAction(proTableRef)}
    rowKey={"id"}
    theme={themeToken.proTableToken}
    headerProps={{
      operatorProps: {
        btnList: [
          { innerType: "create" },
          { innerType: "edit" },
          { innerType: "delete" }
        ],
        createOrEditProps: {
          modalProps: {
            width: "40%"
          },
          CreateOrEditContent: CreateOrEdit,
          getModalTitle: (rowKey) => rowKey ? "编辑代理商" : "创建代理商",
        },
      },
      filterProps: {
        maxWidth: "30%",
        filterItems
      }
    }}
    contentProps={{
      tableProps: {
        columns,
      }
    }}
    onError={(msg) => console.error(msg)}
  />

}

export default List;

const getColumns = () => {
  const { commonStatusList } = getEnv().globalConfig;
  const statusToInfo = helper.convertArrayToObj(commonStatusList);

  const columns: TableType.ColumnsType<RespDataType.AgentItem> = [
    {
      title: '代理商名称',
      dataIndex: 'name',
    },
    {
      title: '联系人',
      dataIndex: 'linkman',
      render: (value) => value || "-",
    },
    {
      title: '联系人电话',
      dataIndex: 'linkmanPhone',
      render: (value) => value || "-",
    },
    {
      title: '地址',
      dataIndex: 'address',
      render: (value) => value || "-",
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, record) => {
        const { color, label } = statusToInfo[record.status];
        return <Badge color={color} text={label} />
      }
    }
  ];

  return columns;
}
